﻿Imports System.Windows.Forms
Imports log4net

Public Class ExceptionHandler

    Private Shared WithEvents _instance As ExceptionHandler

    Public Shared Function GetInstance() As ExceptionHandler
        If _instance Is Nothing Then _
            _instance = New ExceptionHandler
        Return _instance
    End Function

    Private _useLog4Net As Boolean
    Private _useForm As Boolean

    Private _ilog As Ilog

    Private Sub New()
        _useLog4Net = True
        _useForm = True
        _ilog = LogManager.GetLogger(GetType(ExceptionHandler))
    End Sub

    Public Property UseLog4Net As Boolean
        Get
            Return _useLog4Net
        End Get
        Set(ByVal value As Boolean)
            _useLog4Net = value
        End Set
    End Property

    Public Property UseForm As Boolean
        Get
            Return _useForm
        End Get
        Set(ByVal value As Boolean)
            _useForm = value
        End Set
    End Property

    Public Sub HandleException(ByVal ex As Exception)

        If _useLog4Net Then _
                   _ilog.Fatal(ex.Message) : _ilog.Fatal(ex.StackTrace)

        If UseForm Then _
            Dim dr As DialogResult = (New ExceptionForm).ShowDialog(ex)

    End Sub

    Public Shared Sub HandleUnhandledExceptions()

        Dim domain As AppDomain = AppDomain.CurrentDomain

        Exit Sub

        AddHandler domain.UnhandledException, AddressOf ExceptionHandler.UnhandledExceptionHandler
        AddHandler Application.ThreadException, AddressOf ExceptionHandler.UnhandledThreadExceptionHandler

    End Sub

    Private Shared Sub UnhandledExceptionHandler(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
        MessageBox.Show(e.ExceptionObject.ToString(), "Unhandled Exception")
    End Sub

    Private Shared Sub UnhandledThreadExceptionHandler(ByVal sender As Object, ByVal e As Threading.ThreadExceptionEventArgs)
        MessageBox.Show(e.Exception.ToString(), "Unhandled Thread Exception")
    End Sub


End Class
